package com.tools.ad.manager;

import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.daps.weather.DapWeatherActivity;
import com.daps.weather.base.e;
import com.daps.weather.bean.currentconditions.CurrentCondition;
import com.hm.adsbuisiness.bean.RawAd;
import com.hm.adsbuisiness.bean.nativead.BatRawNativeAd;
import com.hm.base.android.mob.AMApplication;
import com.swipe.SwipeMgr;
import com.swipe.ui.ao;
import com.tools.ad.ADGAConstant;
import com.tools.ad.ADModule;
import com.tools.ad.EntranceType;
import com.tools.ad.R;
import com.tools.ad.adscene.AdStrategyScene;
import com.tools.ad.ui.view.SwipeItemViewHolder;
import com.tools.ad.util.GARecordUtils;
import com.tools.ad.util.WindowLayoutParamsUtil;
import com.yanzhenjie.permission.AndPermission;

import java.lang.ref.WeakReference;
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;

import d.a;

/**
 * Created by ChenLi on 2018/2/8.
 */

public class InnerHookManager {

    private static long lastShowWeatherTime = 0l;
    private static String weatherUrl = "";
    private static WeakReference<DapWeatherActivity> mDapWeatherActivityRef;


    /**
     * hook滑动事件一
     *
     * @param thiz
     * @return
     */
    public static WindowManager.LayoutParams swipeTriggerViewHook(Object thiz) {
        WindowManager.LayoutParams layoutParams = null;
        try {
            LinearLayout aq = (LinearLayout) thiz;
            Field c = com.swipe.ui.aq.class.getDeclaredField("c");
            c.setAccessible(true);
            layoutParams = (WindowManager.LayoutParams) c.get(aq);

            if (AndPermission.checkOverlayPermission(AMApplication.getInstance())) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        return layoutParams;
    }

    /**
     * hook滑动事件二
     *
     * @param thiz
     * @return
     */
    public static void swipeTriggerLayoutHook(Object thiz) {
        try {
            Field r = com.swipe.e.class.getDeclaredField("r");
            r.setAccessible(true);

            WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
            if (AndPermission.checkOverlayPermission(AMApplication.getInstance())) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
            layoutParams.format = -2;
            layoutParams.flags = 16777224;
            layoutParams.gravity = 51;
            layoutParams.width = 1;
            layoutParams.height = -1;
            r.set(thiz, layoutParams);

            Field e = com.swipe.e.class.getDeclaredField("e");
            e.setAccessible(true);
            Context context = (Context) e.get(thiz);

            Field q = com.swipe.e.class.getDeclaredField("q");
            q.setAccessible(true);
            View view = new View(context);
            q.set(thiz, view);

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    /**
     * hook快划总视图item
     *
     * @param thiz
     */
    public static void swipeSlideReloadHook(Object thiz) {
        try {

            Class SlideMenuViewClass = thiz.getClass();

            Field fielM = SlideMenuViewClass.getDeclaredField("m");
            Field fielN = SlideMenuViewClass.getDeclaredField("n");
            Field fielC = SlideMenuViewClass.getDeclaredField("c");
            Field fielAa = SlideMenuViewClass.getDeclaredField("aa");

            fielAa.setAccessible(true);
            fielM.setAccessible(true);
            fielN.setAccessible(true);
            fielC.setAccessible(true);

            com.swipe.i.w w = (com.swipe.i.w) fielN.get(thiz);
            Field fielWa = w.getClass().getDeclaredField("a");
            fielWa.setAccessible(true);

            com.swipe.ui.a[] c = (com.swipe.ui.a[]) fielC.get(thiz);
            for (com.swipe.ui.a locala : c) {
                locala.a();
            }

            for (int i = 0; i < 3; i++) {
                Field fielE = SlideMenuViewClass.getDeclaredField("e");
                fielE.setAccessible(true);
                com.swipe.h.b[] e = (com.swipe.h.b[]) fielE.get(thiz);
                List localList = e[i].a();
                if ((i == 1) && (localList.size() < 9)) {
                    Field fieldL = SlideMenuViewClass.getDeclaredField("l");
                    fieldL.setAccessible(true);
                    localList.add(fieldL.get(thiz));
                }

                if (i == 0) {
                    AMApplication application = AMApplication.getInstance();
                    ADModule adModule = (ADModule) application.getSubModule(ADModule.MODULE_KEY);
                    AdStrategyScene adScene = adModule.getAdSceneManager().getAdScene(EntranceType.SWIPE_INDICATE_RECENT);
                    adScene.load(true);
                    RawAd rawAd = adScene.getBatRawNativeAd();
                    if (rawAd != null && rawAd instanceof BatRawNativeAd) {
                        if (localList.size() == 9) {
                            localList.remove(8);
                        }
                        localList.add(rawAd);
                    }
                }

                Field fielD = SlideMenuViewClass.getDeclaredField("d");
                fielD.setAccessible(true);
                com.swipe.b.d[] d = (com.swipe.b.d[]) fielD.get(thiz);
                d[i].b(localList);

            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void swipeSlideReloadOrigin(Object thiz) {

    }

    /**
     * hook快划item适配器
     *
     * @param thiz
     */
    public static View swipeItemgetViewHook(Object thiz, int paramInt, View paramView, ViewGroup paramViewGroup) {
        AMApplication imContext = AMApplication.getInstance();
        try {
            com.swipe.b.d adapterD = (com.swipe.b.d) thiz;
            Class adapterClass = thiz.getClass();
            Field fielA = adapterClass.getDeclaredField("a");
            fielA.setAccessible(true);
            Context context = (Context) fielA.get(thiz);
            if (paramInt >= adapterD.getCount()) {
                return paramView;
            }
            Object localnObject = adapterD.getItem(paramInt);
            Class localnClass = localnObject.getClass();
            SwipeItemViewHolder localg;
            if ((paramView != null) && (!(localnObject instanceof BatRawNativeAd)) && (!(localnClass.getName().equals("com.swipe.h.a.d")))) {
                localg = (SwipeItemViewHolder) paramView.getTag();
            } else {
                localg = new SwipeItemViewHolder();
                paramView = View.inflate(context, R.layout.fan_menu_item_layout, null);
                localg.a = ((ImageView) paramView.findViewById(R.id.image_icon));
                localg.b = ((TextView) paramView.findViewById(R.id.app_name));
                localg.c = ((ImageView) paramView.findViewById(R.id.del_icon));
                localg.d = ((ImageView) paramView.findViewById(R.id.ad_label));
                localg.e = localnClass.getName().equals("com.swipe.h.a.d");
                paramView.setTag(localg);
            }

            if ((localnObject instanceof BatRawNativeAd)) {
                BatRawNativeAd batRawNativeAd = (BatRawNativeAd) localnObject;
                String title = batRawNativeAd.getTitle();
                String iconUrl = batRawNativeAd.getIconUrl();
                if (!TextUtils.isEmpty(iconUrl)) {
                    Glide.with(imContext).load(iconUrl).placeholder(com.hm.adsui.R.drawable.defualt_icon_fullscreen).error(com.hm.adsui.R.drawable.defualt_icon_fullscreen)
                            .dontAnimate().diskCacheStrategy(DiskCacheStrategy.SOURCE).into(localg.a);
                }
                if (!TextUtils.isEmpty(title)) {
                    localg.b.setText(title);
                }
                batRawNativeAd.registerViewForInteraction(paramView);
            } else {

                if (localnClass.getName().equals("com.swipe.h.a.d")) {
                    localg.d.setVisibility(View.VISIBLE);
                    int i = context.getResources().getDimensionPixelOffset(R.dimen.duswipe_menu_item_padding_left);
                    int j = context.getResources().getDimensionPixelOffset(R.dimen.duswipe_menu_item_padding_top);
                    localg.a.setPadding(i, j, i, 0);
                    localg.d.setPadding(i, j, 0, 0);
                    Method bMethod = localnClass.getMethod("b", View.class);
                    bMethod.invoke(localnObject, paramView);
                    Method eMethod = localnClass.getMethod("e");
                    com.duapps.ad.DuNativeAd duNativeAd = (com.duapps.ad.DuNativeAd) eMethod.invoke(localnObject);
                    a.a().a(duNativeAd.getIconUrl(), localg.a);
                } else {
                    Method bMethod = localnClass.getMethod("b");
                    bMethod.setAccessible(true);
                    localg.a.setImageDrawable((Drawable) bMethod.invoke(localnObject));
                    localg.d.setVisibility(View.INVISIBLE);
                }

                Method aMethod = localnClass.getMethod("a");
                aMethod.setAccessible(true);
                String title = (String) aMethod.invoke(localnObject);
                localg.b.setText(title);

                Field fielB = adapterClass.getDeclaredField("b");
                fielB.setAccessible(true);
                com.swipe.b.f b = (com.swipe.b.f) fielB.get(thiz);
                if ((null != b) && (b.a())) {
                    Method cMethod = localnClass.getMethod("c");
                    localg.c.setVisibility((boolean) cMethod.invoke(localnObject) ? View.INVISIBLE : View.VISIBLE);
                } else {
                    localg.c.setVisibility(View.INVISIBLE);
                }
                paramView.setRotation(0.0F);

                Constructor eConstructor = Class.forName("com.swipe.b.e").getDeclaredConstructor(com.swipe.b.d.class, Integer.TYPE);
                eConstructor.setAccessible(true);
                View.OnClickListener onClickListener = (View.OnClickListener) eConstructor.newInstance(adapterD, paramInt);
                localg.c.setOnClickListener(onClickListener);

            }

        } catch (Exception e) {

        }
        if (paramView == null) {
            paramView = View.inflate(AMApplication.getInstance(), R.layout.fan_menu_item_layout, null);
        }
        return paramView;
    }

    public static View swipeItemgetViewOrigin(Object thiz, int paramInt, View paramView, ViewGroup paramViewGroup) {
        return null;
    }

    public static void swipeShowHook(Object thiz, ao direct) {

        AMApplication imContext = AMApplication.getInstance();
        ADModule aDModule = (ADModule) imContext.getSubModule(ADModule.MODULE_KEY);
        if (!aDModule.getADSharedPrefManager().getSwipeAdEnable()) {
            return;
        }


        if (direct == ao.a) {
            if ((System.currentTimeMillis() - lastShowWeatherTime) > 500) {
                lastShowWeatherTime = System.currentTimeMillis();
                GARecordUtils.report(AMApplication.getInstance(), ADGAConstant.C_FUNC, ADGAConstant.A_SHOW, ADGAConstant.FUNC_SHOW_SWIPE_WEATHER);
                Intent intent = new Intent(AMApplication.getInstance().getBaseContext(), DapWeatherActivity.class);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                AMApplication.getInstance().startActivity(intent);
            }
        } else {
            try {
                swipe(direct);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
        }
    }

    public static void swipe(ao direct) throws IllegalAccessException, NoSuchFieldException {
        SwipeMgr mgr = SwipeMgr.getInstance();

        if (!mgr.isSwipeEnable()) {
            return;
        }

        Field field = SwipeMgr.class.getDeclaredField("j");
        field.setAccessible(true);
        boolean isShow = field.getBoolean(mgr);
        if (isShow) {
            return;
        }

        Field field1 = SwipeMgr.class.getDeclaredField("c");
        field1.setAccessible(true);
        com.swipe.e reflect_c = (com.swipe.e) field1.get(mgr);

        //解决8.0 快滑不出现的原因
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            Field d = com.swipe.e.class.getDeclaredField("d");
            d.setAccessible(true);
            WindowManager.LayoutParams layoutParams = (WindowManager.LayoutParams) d.get(reflect_c);
            if (AndPermission.checkOverlayPermission(AMApplication.getInstance())) {
                layoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
            } else {
                layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST;
            }
        }

        boolean show = reflect_c == null ? false : reflect_c.a(direct);
        if (show) {
            Field receiver_f = SwipeMgr.class.getDeclaredField("f");
            receiver_f.setAccessible(true);
            com.swipe.i.t reflect_receiver_f = (com.swipe.i.t) receiver_f.get(mgr);

            Field filter_h = SwipeMgr.class.getDeclaredField("h");
            filter_h.setAccessible(true);
            IntentFilter reflect_filter_h = (IntentFilter) filter_h.get(mgr);

            AMApplication.getInstance().registerReceiver(reflect_receiver_f, reflect_filter_h);

            Field receiver_g = SwipeMgr.class.getDeclaredField("g");
            receiver_g.setAccessible(true);
            com.swipe.i.r reflect_receiver_g = (com.swipe.i.r) receiver_g.get(mgr);

            Field filter_i = SwipeMgr.class.getDeclaredField("i");
            filter_i.setAccessible(true);
            IntentFilter reflect_filter_i = (IntentFilter) filter_i.get(mgr);

            AMApplication.getInstance().registerReceiver(reflect_receiver_g, reflect_filter_i);
        }

    }

    public static void swipeShowOrigin(Object thiz, ao direct) {

    }

    public static void WeatherClickHook(Object thiz, View v) {
        Log.i("IHM", "WC");
        Class<DapWeatherActivity> clazz = DapWeatherActivity.class;
        try {
            Field field = clazz.getDeclaredField("J");
            field.setAccessible(true);
            CurrentCondition cc = (CurrentCondition) field.get(thiz);
            e.b((DapWeatherActivity) thiz, cc.getMobileLink());
            weatherUrl = cc.getMobileLink();
        } catch (Exception e) {
            e.printStackTrace();
        }
        AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_weather_click_hook);

    }

    public static void WeatherUrlJump(Context context, String url) {
        Log.i("IHM", "WUrl");

        if (url.contains("current-weather")) {
            weatherUrl = url;
            AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_weather_click_hook);
            GARecordUtils.report(AMApplication.getInstance(), ADGAConstant.C_FUNC, ADGAConstant.A_CLICK, ADGAConstant.FUNC_WEATHER_CLICK_TODAY);
        } else if (url.contains("daily-weather-forecast")) {
            weatherUrl = url;
            AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_weather_click_hook);
            GARecordUtils.report(AMApplication.getInstance(), ADGAConstant.C_FUNC, ADGAConstant.A_CLICK, ADGAConstant.FUNC_WEATHER_CLICK_WEEK);
        }
    }

    public static void WeatherUrlJumpOrigin(Context context, String url) {

    }

    public static void showWeatherUrl(Context ctx) {
        try {
            String url = weatherUrl + "&partner=baidudap";
            Intent var2 = new Intent();
            var2.setAction("android.intent.action.VIEW");
            var2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            Uri var3 = Uri.parse(url);
            var2.setData(var3);
            ctx.startActivity(var2);

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static void WeatherClickOrigin(Object thiz, View v) {

    }

    public static void swipeLoadAdHook(Object thiz) {
        AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_swipe_load_ad_hook);
    }

    public static void swipeLoadAdOrigin(Object thiz) {

    }

    public static void weatherLogHook(String tag, String content) {
        if (tag.contains("DapWeatherActivity")&&content.contains("isfloatSearchWindowShow:")) {
            AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_weather_close_hook);
        }
    }

    public static void weatherLogOrigin(String tag, String content) {

    }

    public static void addAdToSwipe(View view) throws NoSuchFieldException, IllegalAccessException {
        if (view == null) {
            return;
        }

        Field field = SwipeMgr.class.getDeclaredField("c");
        field.setAccessible(true);
        com.swipe.e c = (com.swipe.e) field.get(SwipeMgr.getInstance());

        Field field1 = com.swipe.e.class.getDeclaredField("B");
        field1.setAccessible(true);
        FrameLayout b = (FrameLayout) field1.get(c);
        b.addView(view);
    }

    public static void weatherLoadAdHook(Object thiz) throws NoSuchFieldException, IllegalAccessException {
        WindowLayoutParamsUtil.setWindowShowWhenLocked((DapWeatherActivity) thiz, true);

        Field field = DapWeatherActivity.class.getDeclaredField("r");
        field.setAccessible(true);
        RelativeLayout r = ((DapWeatherActivity) thiz).findViewById(R.id.dap_weather_layout_weather_ad);
        field.set(thiz, r);

        Field field1 = DapWeatherActivity.class.getDeclaredField("c");
        field1.setAccessible(true);
        d.a c = a.a();
        field1.set(thiz, c);
        AMApplication.getInstance().handleMobEmptyMessage(R.id.msg_weather_load_ad_hook);
        if (mDapWeatherActivityRef == null || mDapWeatherActivityRef.get() == null) {
            Log.i("innerHookManager", "DapWeatherActivity is null");
        }
        mDapWeatherActivityRef = new WeakReference<DapWeatherActivity>((DapWeatherActivity) thiz);
    }

    public static void weatherLoadAdOrigin(Object thiz) {

    }

    public static void addAdToWeather(View view) throws NoSuchFieldException, IllegalAccessException {
        if (view == null || mDapWeatherActivityRef == null || mDapWeatherActivityRef.get() == null) {
            return;
        }
        //r为广告的容器
        Field field = DapWeatherActivity.class.getDeclaredField("r");
        field.setAccessible(true);
        RelativeLayout r = (RelativeLayout) field.get(mDapWeatherActivityRef.get());
        r.removeAllViews();
        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
        params.addRule(RelativeLayout.CENTER_IN_PARENT);
        r.addView(view, params);
        r.setVisibility(View.VISIBLE);
    }

    public static void clear() {
        if (mDapWeatherActivityRef != null) {
            mDapWeatherActivityRef.clear();
        }
        weatherUrl = null;
    }
}
